import { observable, computed } from 'mobx';
import { Promise } from 'drunk-base';
import * as Validator from '../service/Validator';
import { login } from '../service/Auth';

export interface ILoginModel {
    login: string;
    password: string;
}

export class LoginModel implements ILoginModel {

    private isSubmiting: boolean;

    @observable login: string;
    @observable password: string;
    @observable rememberMe = false;

    @computed get loginValid() { return Validator.notEmpty(this.login); }
    @computed get passwordValid() { return Validator.notEmpty(this.password); }

    submit() {
        if (this.isSubmiting) {
            return Promise.reject({ success: false, message: `正在提交，请勿重复操作` });
        }

        let result = this.validate();

        if (!result.success) {
            return Promise.reject(result);
        }

        this.isSubmiting = true;
        return login(this.login, this.password, this.rememberMe).then(
            res => {
                this.isSubmiting = false;
                return { success: true, message: "登录成功" };
            },
            e => {
                this.isSubmiting = false;
                return Promise.reject({ success: false, message: `登录失败，${e.res.message}` });
            }
        );
    }

    validate() {
        let success = false;
        let message = "";

        if (!this.loginValid) {
            message = `请输入正确的用户名或邮箱`;
        }
        else if (!this.passwordValid) {
            message = `请输入密码`;
        }
        else {
            success = true;
        }
        return { success, message };
    }
}